var gulp = require("gulp");
var connect = require("gulp-connect");
var sass = require("gulp-sass");
sass.compiler = require("node-sass");
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const cssmin = require('gulp-cssmin');
var proxy = require('http-proxy-middleware');


gulp.task("connect",async ()=>{
    return connect.server({
        root:"dist",
        livereload:true,
        port:3000,
        middleware : function(){
            return [
                  // 表示在地址栏里面输入的东西是什么 : 
                  proxy('/pxx',  {
                      //代理的目标地址
                      target: 'https://mobile.yangkeduo.com/proxy/api/api/spike/promotion/list/spike',
                      changeOrigin:true,
                      pathRewrite:{//路径重写规则 
                          '^/pxx':''
                      }
                  })
              ]
       }

    });
})

gulp.task("html",async ()=>{
    return gulp.src("./src/page/*.html")
                .pipe(gulp.dest("./dist/page"))
                .pipe(connect.reload());
})

gulp.task("css",async ()=>{
    return gulp.src("./src/styles/*.css")
                .pipe(gulp.dest("./dist/styles"))
                .pipe(connect.reload());
})

gulp.task("all",async ()=>{
    return gulp.src("./src/**/*")
                .pipe(gulp.dest("./dist"))
                .pipe(connect.reload());
})

gulp.task("sass",async ()=>{
    return gulp.src("./src/styles/*.scss")
                .pipe(sass().on("error",sass.logError))
                .pipe(gulp.dest("./dist/styles"))
                .pipe(connect.reload());
})
gulp.task("sass-build" , async ()=>{
    return gulp.src(["./src/styles/*.scss"])
          .pipe(sass().on('error', sass.logError))
          .pipe(cssmin())
          .pipe(gulp.dest("./dist/styles/"))
})

//
gulp.task("javascripts" , async ()=>{
    await  gulp.src(["./src/javascripts/*.js"])
          .pipe(babel({
                presets: ['@babel/env']
          }))
          .pipe(uglify())
          .pipe(gulp.dest("./dist/javascripts"))
})
gulp.task("javascripts-dev" , async ()=>{
    await  gulp.src(["./src/javascripts/*.js"])
          .pipe(gulp.dest("./dist/javascripts"))
          .pipe(connect.reload()) 
})

gulp.task("watch",async ()=>{
    await gulp.watch("./src/page/*.html",gulp.series("html"));
    await gulp.watch("./src/styles/*.css",gulp.series("css"));
    await gulp.watch("./src/styles/*.scss",gulp.series("sass"));
    await gulp.watch("./src/javascripts/*.js",gulp.series("javascripts-dev"));
})

gulp.task("default",gulp.parallel("connect","watch"));
//parallel:异步执行指令
gulp.task("build" , gulp.series("javascripts" , "sass-build"));
//series:同步执行指令